<template>
  <div class="breadcrumb">
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 默认样式紧挨着，这里的el-breadcrumb设置在全局样式文件 global.css中 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主体区域 -->
    <el-card class="box-card">
      <el-row class="mianbaoxie">
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 信息展示部分 -->
      <el-table :data="roleList" border stripe>
        <!-- border：显示边框   stripe：隔行变色 -->
        <el-table-column type="index" lable="#"></el-table-column>
        <!-- 扩展栏 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i == 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteAuthById(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 == 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteAuthById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 渲染三级权限 -->
                    <el-row>
                      <el-col>
                        <el-tag
                          type="warning"
                          :span="6"
                          v-for="item3 in item2.children"
                          :key="item3.id"
                          closable
                          @close="deleteAuthById(scope.row, item3.id)"
                        >
                          {{ item3.authName }}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="assignAuth(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的消息框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="authDialogVisible"
      width="30%"
      :before-close="handleClose"
      @close="clearData()"
    >
      <el-tree
        :data="authTree"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkKeys"
        :props="defaultProps"
        ref="authRef"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="authDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitAuthTree()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 权限列表集合
      roleList: [],
      authDialogVisible: false,
      //权限树形集合
      authTree:[],
      // 勾选的权限id 集合
      checkKeys: [],
      // 树形组件子类和显示属性名定义集合
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 当前消息框所属的角色 ID
      roleId : '',
    };
  },
  created() {
    this.getRoles();
  },
  methods: {
    async getRoles() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        this.$message.error("权限列表获取失败！");
      }
      this.roleList = res.data;
    },
    async deleteAuthById(scope, roleId) {
      const confirmResult = await this.$confirm(
        "此操作将删除权限，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); /* 如果有异常就抛出 */
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${scope.id}/rights/${roleId}`
      );
      if (res.meta.status != 200) {
        this.$message.error("权限删除失败！");
      }
      //   this.getUserList();
      // 这里使用数组替换会使扩展框关闭
      scope.children = res.data;
    },
    // 关闭消息框前提醒
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 点击分配权限按钮触发的事件
    async assignAuth(scope) {
      console.log("scope:");
      console.log(scope);
      const {data:res} = await this.$http.get('rights/tree');
      if(res.meta.status != 200){
          this.$message.error('权限数据获取失败')
      }
      this.authTree = res.data;
      this.getNodeList(scope, this.checkKeys);
      this.authDialogVisible = true;
      this.roleId = scope.id
    },
    // 计算所有需要勾选的所有结点ID
    getNodeList(node,nodeList){
        if(!node.children){
            return nodeList.push(node.id);
        }
        node.children.forEach(childNode => {
            this.getNodeList(childNode, nodeList)
        });
    },
    // 清空勾选数组
    clearData(){
        this.checkKeys = []
    },
    // 提交勾选的结点ID数组
    async commitAuthTree(){
        // 加...是为了组成[id]，模式，不然就是[[id],[id]] 
        const list = [...this.$refs.authRef.getCheckedKeys(),
                      ...this.$refs.authRef.getHalfCheckedKeys()];
        console.log(list);
        const idStr =list.join(',');
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
          rids:idStr
        })
        if(res.meta.status != 200){
          this.$message.error('权限更新失败！')
        }
        this.$message.success('权限更新成功！')
        this.getRoles();
        this.authDialogVisible = false;
    }
  },
};
</script>

<style scoped lang="less">
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
